//
//  FirstRegisterController.m
//  JF_New_DYKT
//
//  Created by 陈雷 on 2017/8/24.
//  Copyright © 2017年 陈雷. All rights reserved.
//

#import "FirstRegisterController.h"
#import "SecondRegisterController.h"
#import "JFSelectAreaB.h"


@interface FirstRegisterController ()

@property (weak, nonatomic) IBOutlet BaseTextfiled *nickNameTf;//昵称
@property (weak, nonatomic) IBOutlet BaseTextfiled *cityTf;//城市
@property (weak, nonatomic) IBOutlet BaseTextfiled *sexTf;//性别
@property (weak, nonatomic) IBOutlet UIButton *headImv;
@property (nonatomic,copy) NSString *areaStr;//地区



@end

@implementation FirstRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    
    UIButton *leftButton = [[UIButton alloc]init];
    leftButton.frame = CGRectMake(0, 0, 11, 20);
    [leftButton setBackgroundImage:[UIImage imageNamed:@"allBack.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItems = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    //解决按钮不靠左 靠右的问题.
    UIBarButtonItem *nagetiveSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                   target:nil action:nil];
    self.navigationItem.leftBarButtonItems = @[nagetiveSpacer, leftBarButtonItems];

    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleAction) name:@"register" object:nil];
    
    
    if ([self.fromWhere isEqualToString:@"wx"] || [self.fromWhere isEqualToString:@"qq"]) {
    
        if ([self.login_registerModel.sex isEqualToString:@"1"]) {
            self.sexTf.text = @"男";
        }else{
            self.sexTf.text = @"女";
        }
        
        self.nickNameTf.text = self.login_registerModel.nickname;
        
        [self.headImv sd_setImageWithURL:[NSURL URLWithString:self.login_registerModel.image_base64] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headerImgZhanWei.png"]];
        
    }else{
        self.login_registerModel = [[Login_registerModel alloc]init];
    }
    [self notificationAction];
}

- (void)handleAction{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissAction" object:nil userInfo:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"register" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setShadowImage:[JFCrazyTool imageWithColor:[UIColor whiteColor]]];
    [self.navigationController.navigationBar setBackgroundImage:[JFCrazyTool imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
}


- (void)backAction{

    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];

}

#pragma mark- 更新头像
- (IBAction)updateHeadImv:(UIButton *)sender {
    NSLog(@"更新头像");
    
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVc addAction:takePhotoAction];
    [alertVc addAction:photoAlbumAction];
    [alertVc addAction:cancelAction];
    
    [self presentViewController:alertVc animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *img = info[@"UIImagePickerControllerEditedImage"];
    //对图片进行压缩处理
    img = [self imageWithImageSimple:img scaledToSize:CGSizeMake(200, 200) targetKB:100];
    
    NSData *data = UIImagePNGRepresentation(img);
    
    NSString *headerStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    [self.headImv setImage:img forState:UIControlStateNormal];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/Personal/headUploadImage",kDomainName];
    
    NSDictionary *paraDic = @{@"imgbase64":headerStr};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];

    
    __weak typeof(self) weakSelf = self;
    
    [request post:urlStr params:paraDic success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {

            weakSelf.login_registerModel.image_base64 = responseObject[@"data"];
            
            [JKToast showWithText:responseObject[@"message"]];
            
        }else{
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)handleAction:(UIButton *)sender {
    NSLog(@"下一步");
    SecondRegisterController *secondVc = [[SecondRegisterController alloc]init];
    secondVc.fromWhere = self.fromWhere;
    
    if ([self.sexTf.text isEqualToString:@"男"]) {
        self.login_registerModel.sex = @"1";
    }else{
        self.login_registerModel.sex = @"0";
    }
    
    self.login_registerModel.nickname = self.nickNameTf.text;
    
    self.login_registerModel.region = self.areaStr;
    
    
    secondVc.login_registerModel = self.login_registerModel;
    
    
    if (self.sexTf.text.length <= 0 ) {
        [JKToast showWithText:@"请选择性别！"];
        return;
    }else if (_login_registerModel.nickname.length <= 0){
        [JKToast showWithText:@"请填写昵称！"];
        return;
    }else if (_login_registerModel.image_base64.length <= 0){
        [JKToast showWithText:@"请上传您的头像！"];
        return;
    }else if (_login_registerModel.region.length <= 0){
        [JKToast showWithText:@"请选择您所在的地区！"];
        return;
    }
    
    [self.navigationController pushViewController:secondVc animated:YES];
}

#pragma mark- 对图片进行压缩
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize targetKB: (NSInteger)KB
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    NSData *data = UIImageJPEGRepresentation(newImage, 1);
    
    //kb为0时没有设定图片必须小于某个数
    if (KB != 0) {
        while (data.length/1024 > KB) {
            
            //1.改变size的方法压缩
            // Create a graphics image context
            newSize = CGSizeMake(newSize.width*.8, newSize.height*.8);
            UIGraphicsBeginImageContext(newSize);
            
            // Tell the old image to draw in this new context, with the desired
            // new size
            [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
            
            // Get the new image from the context
            newImage = UIGraphicsGetImageFromCurrentImageContext();
            
            // End the context
            UIGraphicsEndImageContext();
            
            data = UIImageJPEGRepresentation(newImage, 1);
            
        }
    }
    
    return newImage;
}

- (IBAction)selectSexAction:(UIButton *)sender {
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexTf.text = @"男";
    }];
    
    UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexTf.text = @"女";
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVc addAction:takePhotoAction];
    [alertVc addAction:photoAlbumAction];
    [alertVc addAction:cancelAction];
    
    [self presentViewController:alertVc animated:YES completion:nil];
    
    
}

- (IBAction)selectCityAction:(UIButton *)sender {
    
    __weak typeof(self) weakSelf = self;
    
    JFSelectAreaB *selectV = [[JFSelectAreaB alloc]initWithFrame:CGRectMake(0, 0, KSCreenWidth, KSCreenHeight) completeBlock:^(NSString *areaStr) {
        weakSelf.areaStr = areaStr;
        weakSelf.cityTf.text = [areaStr stringByReplacingOccurrencesOfString:@";" withString:@""];
    }];
    [self.navigationController.view addSubview:selectV];
    
}


- (void)notificationAction{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyBoardWillShow:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.view.transform = CGAffineTransformMakeTranslation(0, -keyBoardHeight+80);
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
    
}

- (void)keyBoardWillHide:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.view.transform = CGAffineTransformIdentity;
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
}



@end
